#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include "comm.hpp"

int main(){
    // 1、创建管道文件，只需要创建一次
    //设置当前进程的掩码
    umask(0);
    int n = mkfifo(fifoname.c_str(), mode);
    cout << "create fifo success" << endl;

    if (n!=0)
    {
        cout << errno << " : " << strerror(errno) << endl;
        exit(1);
    }

    // 2、打开相同文件
    int rfd = open(fifoname.c_str(), O_RDONLY);
    if(rfd <= 0){
        cout << errno << " : " << strerror(errno) << endl;
        exit(2);
    }
    cout << "open fifo success" << endl;

    // 3、通信
    char buffer[NUM];
    while (1)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0){
            buffer[n] = 0;
            cout << "client : " << buffer << endl;
        }else if(n == 0){
            cout << "client quit, exit" << endl;
            break;
        }else{
            cout << errno << " : " << strerror(errno) << endl;
            break;
        }
    }

    //关闭不要的fd
    close(rfd);

    //删除fifo
    unlink(fifoname.c_str());

    return 0;
}